<template>
  <div class="page static-add" ref="staticAdd">
    <ContainerItem hasNav :title="title">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="130px"
        class="form-search from-wrapper"
      >
        <ItemWrap>
          <!--				<div class="btn-nav-bg main-title">{{ title }}</div>-->
          <el-form-item label="故障名称：" prop="faultName">
            <el-input
              v-model="form.faultName"
              :disabled="$route.query.flag === 'view'"
              placeholder="请输入故障名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="故障编号：" prop="faultCode">
            <el-input
              v-model="form.faultCode"
              :disabled="$route.query.flag === 'view'"
              placeholder="请输入故障编号"
            ></el-input>
          </el-form-item>

          <el-form-item label="柔直工程">
            <el-select
              @change="handle('converterStation', { project: form.project })"
              v-model="form.project"
              placeholder="请选择"
              collapse-tags
            >
              <el-option
                v-for="item in projectOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="换流站：" prop="converterStation">
            <el-select
              @change="
                handle('deviceType', {
                  project: form.project,
                  converterStation: form.converterStation,
                })
              "
              v-model="form.converterStation"
              filterable
              allow-create
              default-first-option
              placeholder="请选择换流站"
              :disabled="$route.query.flag === 'view'"
              collapse-tags
            >
              <el-option
                v-for="item in converterStationOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备类型：">
            <el-select
              @change="
                handle('factory', {
                  project: form.project,
                  converterStation: form.converterStation,
                  deviceType: form.deviceType,
                })
              "
              v-model="form.deviceType"
              filterable
              allow-create
              default-first-option
              placeholder="请选择设备类型"
              :disabled="$route.query.flag === 'view'"
              collapse-tags
            >
              <el-option
                v-for="item in deviceTypeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="厂家：">
            <el-select
              @change="
                handle('faultType', {
                  project: form.project,
                  converterStation: form.converterStation,
                  deviceType: form.deviceType,
                  factory: form.factory,
                })
              "
              v-model="form.factory"
              filterable
              allow-create
              default-first-option
              :disabled="$route.query.flag === 'view'"
              placeholder="请选择厂家"
              collapse-tags
            >
              <el-option
                v-for="item in factoryOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备型号：">
            <el-select
              v-model="form.deviceModel"
              placeholder="请选择设备型号"
              :disabled="$route.query.flag === 'view'"
            >
              <el-option
                v-for="(item, idx) in deviceModelOpt"
                :key="idx"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <!--					<el-form-item label="故障设备信息：">-->
          <!--						<el-input-->
          <!--							v-model="form.faultDeviceInfo"-->
          <!--							type="textarea"-->
          <!--							:disabled="$route.query.flag==='view'"-->
          <!--							placeholder="请输入故障设备信息"-->
          <!--						></el-input>-->
          <!--					</el-form-item>-->
          <el-form-item label="是否闭锁：" prop="isAtresia">
            <el-radio-group v-model="form.isAtresia">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否临停：" prop="isPowerOut">
            <el-radio-group v-model="form.isPowerOut">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="投运时间：">
            <el-date-picker
              v-model="form.operationTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              :disabled="$route.query.flag === 'view'"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择投运时间"
            >
            </el-date-picker>
          </el-form-item>
          <!--					<el-form-item label="故障报文：">-->
          <!--						<el-input-->
          <!--							v-model="form.faultMesg"-->
          <!--							type="textarea"-->
          <!--							:disabled="$route.query.flag==='view'"-->
          <!--							placeholder="请输入故障报文"-->
          <!--						></el-input>-->
          <!--					</el-form-item>-->

          <div style="display: flex">
            <el-form-item label="故障报文：" style="width: calc(100% - 80px)">
              <el-input
                v-model="form.faultMesg"
                type="textarea"
                :disabled="$route.query.flag === 'view'"
                placeholder="请输入故障报文"
              ></el-input>
            </el-form-item>
            <el-form-item label="" label-width="20px">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :http-request="uploadImage"
              >
                <div class="upload-btn">识别图片</div>
              </el-upload>
            </el-form-item>
          </div>
          <el-form-item label="技术监督意见：" style="width: calc(100% - 80px)">
            <el-input
                v-model="form.supervisionOpinion"
                :disabled="$route.query.flag === 'view'"
                placeholder="请输入技术监督意见"
            ></el-input>
          </el-form-item>
          <el-form-item label="故障时间：">
            <el-date-picker
              v-model="form.alarmTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              :disabled="$route.query.flag === 'view'"
              placeholder="请选择故障时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="事件概述：">
            <vue-editor
              :editorContent="form.eventOverview"
              ref="eventOverview"
              :action="''"
              :disabled="$route.query.flag === 'view'"
            ></vue-editor>
          </el-form-item>
        </ItemWrap>
        <ItemWrap>
          <el-form-item label="故障类型：" label-width="180px">
            <el-select
              @change="
                handle('faultPart', {
                  project: form.project,
                  converterStation: form.converterStation,
                  deviceType: form.deviceType,
                  factory: form.factory,
                  faultType: form.faultType,
                })
              "
              v-model="form.faultType"
              filterable
              allow-create
              default-first-option
              :disabled="$route.query.flag === 'view'"
              placeholder="请选择故障类型"
              collapse-tags
            >
              <el-option
                v-for="item in faultTypeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="定位部件："
            class="middleWidth"
            prop="faultPart"
            label-width="180px"
          >
            <el-select
              v-model="form.faultPart"
              filterable
              allow-create
              default-first-option
              placeholder="请选择定位部件"
              :disabled="$route.query.flag === 'view'"
              collapse-tags
            >
              <el-option
                v-for="item in faultPartOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="计划消缺时间：" label-width="180px">
            <el-date-picker
              v-model="form.planFinishTime"
              :disabled="$route.query.flag === 'view'"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择计划消缺时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="处理状态：" label-width="180px">
            <el-radio-group
              v-model="form.dealStatus"
              :disabled="$route.query.flag === 'view'"
            >
              <el-radio :label="'已完成'">已完成</el-radio>
              <el-radio :label="'未完成'">未完成</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="实际完成时间：" label-width="180px">
            <el-date-picker
              v-model="form.finishTime"
              type="datetime"
              :disabled="$route.query.flag === 'view'"
              placeholder="请选择实际完成时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="现场检查及处置情况：" label-width="180px">
            <vue-editor
              :editorContent="form.siteDealing"
              ref="siteDealing"
              inputRef="siteDealingInput"
              toEditorRef="siteDealingToRef"
              :action="''"
            ></vue-editor>
          </el-form-item>
          <el-form-item label="返厂检查及试验情况：" label-width="180px">
            <vue-editor
              :editorContent="form.factoryInspection"
              ref="factoryInspection"
              inputRef="factoryInspectionInput"
              toEditorRef="factoryInspectionToRef"
              :action="''"
            ></vue-editor>
          </el-form-item>
          <el-form-item label="原因分析：" label-width="180px">
            <vue-editor
              :editorContent="form.faultAnalyse"
              ref="faultAnalyse"
              inputRef="faultAnalyseInput"
              toEditorRef="faultAnalyseToRef"
              :action="''"
            ></vue-editor>
          </el-form-item>
          <el-form-item label="结论及建议：" label-width="180px">
            <vue-editor
              :editorContent="form.conclusion"
              ref="conclusion"
              inputRef="conclusionInput"
              toEditorRef="conclusionToRef"
              :action="''"
            ></vue-editor>
          </el-form-item>
          <el-form-item label="文档附件：" label-width="180px">
            <el-upload
              ref="upload"
              action="/converter-api/defectLib/uploadDefectFile"
              :data="uploadData"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="form.fileList"
              :on-change="handleUpload"
              :before-upload="handleBefore"
              :disabled="$route.query.flag === 'view'"
            >
              <!--							:auto-upload="false">-->
              <div class="upload-btn">上传附件</div>
            </el-upload>
          </el-form-item>
        </ItemWrap>
      </el-form>
      <ul class="btn-wrapper">
        <li
          class="btn-nav-bg stripe-btn"
          v-if="$route.query.flag !== 'view'"
          @click="save"
        >
          保存
        </li>
        <li class="btn-nav-bg stripe-btn" @click="back">返回</li>
      </ul>
    </ContainerItem>
    <pub-dialog
      title="识别图片结果"
      :top="'10vh'"
      :dialogVisible="dialogVisible"
      dialogVisableRef="dialogVisible"
      @switchVisable="switchVisable"
      btnType="0"
    >
      <page-table
        :tableData="datas"
        :tableLabel="columns"
        :table-height="600"
      ></page-table>
    </pub-dialog>
  </div>
</template>

<script>
import VueEditor from "@/components/VueEditor";
import ItemWrap from "@/components/ItemWrap";
import ContainerItem from "@/components/ContainerItem.vue";
import { Message } from "element-ui";
import { Loading } from "element-ui";
import PubDialog from "@/components/pubDialog";
import PageTable from "@/components/PageTable";

import {
  getDefectDetail,
  getDefectSelect,
  editDefect,
  addDefect,
  getDefectModelList,
  uploadFile,
  exportExcel,
} from "@/api/earlyWarning";

export default {
  name: "Add",
  components: {
    VueEditor,
    ContainerItem,
    ItemWrap,
    PubDialog,
    PageTable,
  },
  data() {
    return {
      projectOption: [],
      deviceTypeOption: [],
      faultTypeOption: [],
      factoryOption: [],
      faultPartOption: [],
      converterStationOption: [],
      uploadData: {},
      title: "新建故障案例",
      form: {
        faultName: "",
        project: "",
        faultCode: "",
        converterStation: "",
        deviceType: "",
        factory: "",
        deviceModel: [],
        isAtresia: "",
        isPowerOut: "",
        operationTime: '',
        faultMesg: "",
        alarmTime: "",
        eventOverview: "",
        faultType: "",
        planFinishTime: "",
        dealStatus: "",
        finishTime: "",
        siteDealing: "",
        factoryInspection: "",
        faultAnalyse: "",
        conclusion: "",
        faultDeviceInfo: "",
        fileList: [],
        faultPart: "",
        upFileList: [],
        supervisionOpinion:''
      },

      deviceModelOpt: [],
      faultTypeOtp: [],
      factorysOption: [],
      rules: {
        faultName: [
          { required: true, message: "请输入故障名称", trigger: "blur" },
        ],
        faultCode: [
          { required: true, message: "请输入故障编号", trigger: "blur" },
        ],
        converterStation: [
          { required: true, message: "请选择换流站", trigger: "change" },
        ],
        alarmTime: [
          { required: true, message: "请选择告警时间", trigger: "change" },
        ],
      },
      fileName: "",
      fileUploadList: [],
      upFile: null,
      dialogVisible: false,
      datas: [],
      columns: [{ label: "识别结果", param: "result" }],
    };
  },

  mounted() {
    let arr = [
      "project",
      "converterStation",
      "deviceType",
      "factory",
      "faultType",
      "faultPart",
    ];
    arr.forEach((item, index) => {
      this.getDefectSelect(item, arr[index + 1]).then((res) => {
        this[item + "Option"] = res;
      });
    });
    this.toScrollClick();
    if (this.$route.query.flag === "add") {
      this.getDefectModelList();
      this.title = "新建故障案例";
    } else {
      this.title =
        this.$route.query.flag === "edit" ? "编辑故障案例" : "故障案例详情";
      Promise.all([this.getDefectModelList()]).then((res) => {
        this.getDefectDetail(this.$route.query.id);
      });
    }
  },
  methods: {
    /**
     * @Description: 查询条件数据获取
     * @param: wantType 将要查询的数据字段
     * @param: curSelectType 当前选择的数据字段
     * @param: curSelectValue 当前选择的数据
     */
    async getDefectSelect(wantType, obj) {
      let params = {
        type: wantType,
      };
      for (let key in obj) {
        params[key] = obj[key];
      }

      let result = await getDefectSelect(params);
      if (
        result.code == 200 &&
        Array.isArray(result.data) &&
        result.data.length
      ) {
        return new Promise((resolve) => {
          let arr = result.data.map((item) => {
            if (item.val) {
              return {
                label: item.val,
                value: item.val,
              };
            }
          });
          resolve(arr);
        });
      }
    },
    handle(wantType, obj) {
      this.getDefectSelect(wantType, obj).then((res) => {
        this[wantType + "Option"] = res;
      });
    },
    // 识别图片
    uploadImage(param) {
      const loading = Loading.service({
        lock: true,
        text: "图片识别中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      // setTimeout(() => {
      //   loading.close();
      // }, 2000);
      const formData = new FormData();
      formData.append("file", param.file);
      uploadFile(formData)
        .then((response) => {
          if (response.code === 200) {
            this.datas = [];
            this.$nextTick(() => {
              // 以服务的方式调用的 Loading 需要异步关闭
              loading.close();
            });
            this.dialogVisible = true;
            response.data.map((item) => {
              this.datas.push({ result: item[0] });
            });
          }
        })
        .catch((response) => {
          this.$nextTick(() => {
            // 以服务的方式调用的 Loading 需要异步关闭
            loading.close();
          });
        });
    },

    // 监听弹窗关闭
    switchVisable(visable, ref) {
      this[ref] = visable;
    },

    //设备型号
    getDefectModelList() {
      return new Promise((resolve) => {
        getDefectModelList().then((res) => {
          if (res.code === 200) {
            res.data.map((item) => {
              this.deviceModelOpt.push({
                label: item,
                value: item,
              });
            });
            resolve(res.data);
          }
        });
      });
    },

    toScrollClick() {
      this.$nextTick(() => {
        let scrollEl = this.$refs.staticAdd;
        scrollEl.scrollTo({ top: 0, behavior: "smooth" });
      });
    },
    // 查询详情
    getDefectDetail(id) {
      getDefectDetail({ defectId: id }).then((res) => {
        if (res.code == 200 && res.data) {
          // this.form = {...res.data};
          // this.form.factory = this.form.factory.split(',');
          // 	this.$refs['eventOverview'].content = this.form.eventOverview
          // 	this.$refs['siteDealing'].content = this.form.siteDealing
          // 	this.$refs['factoryInspection'].content = this.form.factoryInspection
          // 	this.$refs['faultAnalyse'].content = this.form.faultAnalyse
          // 	this.$refs['conclusion'].content = this.form.conclusion
          this.form.id = res.data.id;
          this.form.faultName = res.data.faultName;
          this.form.faultCode = res.data.faultCode;
          this.form.converterStation = res.data.converterStation;
          this.form.deviceType = res.data.deviceType;
          // this.form.factory = res.data.factory.split(",");
          this.form.factory= res.data.factory
          this.form.deviceModel = res.data.deviceModel;
          this.form.operationTime = res.data.operationTime?this.$moment(res.data.operationTime).format("YYYY-MM-DD HH:mm:ss"):res.data.operationTime;
          this.form.faultDeviceInfo = res.data.faultDeviceInfo;
          this.form.faultMesg = res.data.faultMesg;
          this.form.supervisionOpinion=res.data.supervisionOpinion;
          this.form.alarmTime = res.data.alarmTime?this.$moment(res.data.alarmTime).format("YYYY-MM-DD HH:mm:ss"):res.data.alarmTime;
          this.form.faultType = res.data.faultType;
          this.form.planFinishTime = res.data.planFinishTime?this.$moment(res.data.planFinishTime).format("YYYY-MM-DD HH:mm:ss"):res.data.planFinishTime;
          this.form.dealStatus = res.data.dealStatus;
          this.form.finishTime = res.data.finishTime?this.$moment(res.data.finishTime).format("YYYY-MM-DD HH:mm:ss"):res.data.finishTime;
          this.form.faultPart = res.data.faultPart;
          this.form.isAtresia = res.data.isAtresia;
          this.form.project = res.data.project;
          this.form.isPowerOut = res.data.isPowerOut;
          this.fileUploadList = res.data.analyseDoc
            ? res.data.analyseDoc.split(",")
            : [];
          if (this.fileUploadList.length) {
            this.form.fileList = this.fileUploadList.map((item) => {
              return {
                name: item,
                url: window.productiontDocIp + "/docs/" + item,
              };
            });
          }
          this.$refs["eventOverview"].content =
            res.data.eventOverview &&
            res.data.eventOverview.indexOf("data:image/png") !== -1
              ? res.data.eventOverview.replace(
                  "data:image/png",
                  "data:image/jpg"
                )
              : res.data.eventOverview;
          this.$refs["siteDealing"].content =
            res.data.siteDealing &&
            res.data.siteDealing.indexOf("data:image/png") !== -1
              ? res.data.siteDealing.replace("data:image/png", "data:image/jpg")
              : res.data.siteDealing;
          this.$refs["factoryInspection"].content =
            res.data.factoryInspection &&
            res.data.factoryInspection.indexOf("data:image/png") !== -1
              ? res.data.factoryInspection.replace(
                  "data:image/png",
                  "data:image/jpg"
                )
              : res.data.factoryInspection;
          this.$refs["faultAnalyse"].content =
            res.data.faultAnalyse &&
            res.data.faultAnalyse.indexOf("data:image/png") !== -1
              ? res.data.faultAnalyse.replace(
                  "data:image/png",
                  "data:image/jpg"
                )
              : res.data.faultAnalyse;
          this.$refs["conclusion"].content =
            res.data.conclusion &&
            res.data.conclusion.indexOf("data:image/png") !== -1
              ? res.data.conclusion.replace("data:image/png", "data:image/jpg")
              : res.data.conclusion;
        }
      });
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let API = this.$route.query.flag === "edit" ? editDefect : addDefect;
          let params = { ...this.form };
          params.analyseDoc = this.fileUploadList.join(",");
          // params.factory = params.factory.join(",");
          params.eventOverview = this.$refs["eventOverview"].content;
          params.siteDealing = this.$refs["siteDealing"].content;
          params.factoryInspection = this.$refs["factoryInspection"].content;
          params.faultAnalyse = this.$refs["faultAnalyse"].content;
          params.conclusion = this.$refs["conclusion"].content;

          API(params).then((res) => {
            if (res.code == 200) {
              Message.success("保存成功");
              this.$router.push("/earlyWarning");
            }
          });
        } else {
          return false;
        }
      });
    },
    back() {
      this.$router.push("/earlyWarning");
    },

    handleUpload(file, fileList) {
      this.uploadData = {};
    },

    handleBefore(file) {
      this.fileUploadList.push(file.name);
    },
    handleRemove(file, fileList) {},
    handlePreview(file) {
      let url = "/converter-api/defectLib/downloadDefectFile";
      exportExcel(url, { fileName: "/data/files/docs/" + file.name }).then(
        (res) => {
          let url = window.URL.createObjectURL(new Blob([res.data]));
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", file.name);
          document.body.appendChild(link);
          link.click();
        }
      );
      // let href = window.productiontDocIp + '/docs/' + file.name
      // window.open(href)
    },
  },
};
</script>

<style scoped lang="less">
.page.static-add {
  //height: calc(100% - 70px);
  width: 100%;
  height: 100%;
  overflow: auto;
  box-sizing: border-box;
  overflow-y: hidden;
  background-color: rgba(10, 31, 53, 0);
  .container-item-content {
    display: flex;
    justify-content: space-between;
    overflow: hidden;
  }
  .form-search {
    height: calc(100% - 50px);
    padding-bottom: 10px;
    overflow-y: auto;
  }
  .form-search .el-form-item {
    margin-bottom: 15px;
  }

  .btn-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    //position: absolute;
    //right: 30px;
    //top: 23px;
    //z-index: 9999999;
  }

  .item-wrap-container {
    background-color: transparent;
    height: 100%;
    width: 50%;
  }

  .from-wrapper {
    display: flex;
    justify-content: space-between;

    .left-form-wrapper {
      margin-right: 16px;
    }

    .left-form-wrapper,
    .right-form-wrapper {
      width: calc(50% - 8px);
    }

    .left-form-wrapper {
      .item-wrap-container {
        padding: 10px 60px 10px 10px;
      }
    }

    .right-form-wrapper {
      .item-wrap-container {
        padding: 30px 10px 10px 10px;
      }
    }
  }

  .upload-btn {
    width: 58px;
    height: 28px;
    text-align: center;
    line-height: 28px;
    background: linear-gradient(
      180deg,
      rgba(33, 160, 229, 0.6) 0%,
      rgba(39, 100, 165, 0.6) 100%
    );
    box-shadow: inset 0px 0px 10px 0px rgba(63, 255, 236, 0.4);
    opacity: 1;
    border: 1px solid;
    color: rgba(255, 255, 255, 1);
    font-family: Source Han Sans-Bold;
    border-image: linear-gradient(
        0deg,
        rgba(96.00000187754631, 255, 255, 0),
        rgba(96.00000187754631, 255, 255, 1),
        rgba(96.00000187754631, 255, 255, 0)
      )
      1 1;
  }
}
</style>
